﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using UnityEditor;
using UnityEngine;
namespace HDJ.Framework.Core.Editor
{
    public class TableDataDrawTextureField : TableDataDrawFieldBase
    {
        public override Type FieldType => typeof(string);

        public override string Tag => "Texture";

        private UnityEditor.Editor previewEditor1;
        private Texture2D previewTex;
        private object editTextureValue;
        public override object DrawGUI(string text, object value, TableFieldInfo info)
        {
            if (editTextureValue != null)
            {
                value = editTextureValue;
                editTextureValue = null;
            }

            GUILayout.BeginHorizontal();
            value = EditorDrawGUIUtil.DrawBaseValue(text, value);
            if (GUILayout.Button("o", GUILayout.Width(20)))
            {
                ObjectSelectorWindow.Show(GeneralDataModificationWindow.GetInstance(), value.ToString(),
                    new string[] { "Assets/Resources" },
                    typeof(Texture),
                    (assetName, obj) =>
                    {
                        editTextureValue = assetName;
                    }
                    );
            }
            GUILayout.EndHorizontal();
            string content = value.ToString();
            bool isHave = false;
            try
            {
                if (ResourceManager.ExistAssets(content))
                {
                    Texture2D obj = ResourceManager.Load<Texture2D>(content);
                    if (obj)
                    {

                        if (obj != previewTex)
                        {
                            previewEditor1 = UnityEditor.Editor.CreateEditor(obj);
                            previewTex = obj;
                        }
                        previewEditor1.OnPreviewGUI(GUILayoutUtility.GetRect(300, 300), EditorStyles.helpBox);
                        isHave = true;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }

            if (!isHave)
            {
                EditorGUILayout.HelpBox("没有图片 [" + value + "] ！！", MessageType.Error);
            }

            return value;
        }
    }
}

